<?php
/**
 * Created by PhpStorm.
 * User: yann
 * Date: 2019/4/9
 * Time: 下午10:26
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\AuthGroupAccess;
use App\Models\AuthRule;
use Illuminate\Http\Request;

class LoginController extends Controller
{

    public function __construct()
    {
        // 这里额外注意了：官方文档样例中只除外了『login』
        // 这样的结果是，token 只能在有效期以内进行刷新，过期无法刷新
        // 如果把 refresh 也放进去，token 即使过期但仍在刷新期以内也可刷新
        // 不过刷新一次作废
        $this->middleware('auth:admin', ['except' => ['login']]);
        // 另外关于上面的中间件，官方文档写的是『auth:api』
        // 但是我推荐用 『jwt.auth』，效果是一样的，但是有更加丰富的报错信息返回
    }
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = $request->all(['username','password']);
//        return response()->json([
//            'data' => $credentials
//        ]);
        if (! $token = auth('admin')->attempt($credentials)) {
//            return response()->json(['error' => 'Unauthorized'], 401);
            return response()->json([
                'code' => -1,
                'msg' => '用户名或密码错误'
            ]);
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth('admin')->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('admin')->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     * 刷新token，如果开启黑名单，以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('admin')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
//        return response()->json([
//            'access_token' => $token,
//            'token_type' => 'bearer',
//            'expires_in' => auth('admin')->factory()->getTTL() * 60
//        ]);

        $user = auth('admin')->user();

        $groups = authGroupAccess::where('uid',$user->id)->first();
        if ($groups && $groups->group_id) {
            $authRule = AuthRule::where('group_id',$groups->group_id)->get()->toArray();
            $access = array_values(array_unique(array_column($authRule, 'route')));
        } else {
            $access = [];
        }
        return response()->json([
            'code' => 1,
            'msg' => '登陆成功',
            'data' => [
                'token' => $token,
                'expires_in' => auth('admin')->factory()->getTTL() * 60,
                'username' => $user->username,
                'id' => $user->id,
                'access' => $access
            ]
        ]);
    }
}
